package vip.xls8z.learning.nio.channel;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Slf4j
public class NioEchoServer {

    public static void main(String[] args) throws IOException, InterruptedException {
        // 1.获取Selector选择器
        Selector selector = Selector.open();
        // 2.获取通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 3.设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        // 4.绑定连接
        serverSocketChannel.bind(new InetSocketAddress("127.0.0.1", 8091));
        // 5.将通道注册到选择器上,并注册的操作为：“接收”操作
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 6.采用轮询的方式，查询获取“准备就绪”的注册过的操作
        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                NioEchoHandler.executor(serverSocketChannel, selectionKey);
            }
            selectionKeys.clear();
        }
    }

    public static class NioEchoHandler {
        static ExecutorService executorService = Executors.newFixedThreadPool(5);

        public static void executor(ServerSocketChannel serverSocketChannel, SelectionKey selectionKey) {
            ByteBuffer inputBuff = ByteBuffer.allocate(1024);
            ByteBuffer outputBuff = ByteBuffer.allocate(1024);
            try {
                if (selectionKey.isAcceptable()) {
                    log.info("accepted");
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    if (socketChannel == null) {
                        return;
                    }
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ);
                }

                if (selectionKey.isReadable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    if (socketChannel == null) {
                        return;
                    }

                    inputBuff.clear();
                    int length = socketChannel.read(inputBuff);
                    if (length == -1) {
                        socketChannel.close();
                        selectionKey.cancel();
                        return;
                    }

                    inputBuff.flip();
                    log.info("Readable [From Client]: {}", new String(inputBuff.array(), 0, length));

                    socketChannel.register(selectionKey.selector(), SelectionKey.OP_WRITE);
                    selectionKey.selector().wakeup();
                }

                if (selectionKey.isWritable()) {
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    if (socketChannel == null) {
                        return;
                    }
                    String message = "Hello, Client. " + UUID.randomUUID();
                    outputBuff.put(message.getBytes(StandardCharsets.UTF_8));
                    outputBuff.flip();
                    socketChannel.write(outputBuff);
                    log.info("[To Client]: {}", message);

                    socketChannel.register(selectionKey.selector(), SelectionKey.OP_READ);
                    selectionKey.selector().wakeup();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
